package com.fruit.service.order.impl;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fruit.constants.PayConstant;
import com.fruit.mapper.order.OrderMapper;
import com.fruit.pojo.order.DSHOrder;
import com.fruit.pojo.order.Order;
import com.fruit.pojo.order.OrderGoods;
import com.fruit.pojo.pay.PayInfo;
import com.fruit.pojo.user.ComAccount;
import com.fruit.service.order.OrderConfirmManager;
import com.fruit.service.order.OrderHandel;
import com.fruit.service.sms.SmsCodeManager;
import com.fruit.util.CustomUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;


/** 订单
 * 修改时间：2016.07.15
 */
@Service("orderHandelService")
public class OrderHandelService implements OrderHandel{

	@Autowired
	private OrderConfirmManager orderConfirmService;
	
	@Autowired
	private SmsCodeManager smsCodeService;

	@Autowired
	private OrderMapper orderMapper;


	@Override
	public Map<String, Object> autoCancelOrder(DSHOrder dshOrder, int times) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		for(int i=1;i<=times; i++){
			resMap = orderConfirmService.updateAutoCancelOrder(dshOrder);
			ResultInfo ri = (ResultInfo)resMap.get("result");
			if(!StringUtils.equals("again_start", ri.getCode())){
				break;
			}
			if(i < times){
				CustomUtil.sleep(30, 50);
			}
		}
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	
	public void runSaveAutoCancelOrder(final List<Order> orderList,final PayInfo pi){
		new Thread(new Runnable() {
			@Override
			public void run() {
		
				//调用自动退订
				for(int i=0;i<orderList.size();i++){
					Order order = orderList.get(i);
					if( PayConstant.PAY_TYPE_ALL.equals(pi.getPayType())){
						orderConfirmService.newSaveAutoCancelOrder(order.getId());
					}
				}
				
				//发送短信给用户
				String phones = "['" + pi.getPhone() +"']";
				String params = "['" + pi.getCompanyName()+"','"+pi.getRemittanceCode() +"']";
				smsCodeService.sendSmsNotice("user_pay", phones, params);
				
				//发送短信给运营人员
				ComAccount comAccount = orderMapper.getComAss();
				phones = "['" +comAccount.getOperatingPhone()+"']";
				params = "['" + pi.getCompanyName()+"','"+pi.getPhone() +"','"+pi.getOrderCodes()+"']";
				smsCodeService.sendSmsNotice("operate_pay", phones, params);
				
			}
		}).start();
		
		
	}
	
	
	
}
